import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // 首先尝试从数据库获取真实数据
    let project = null
    try {
      project = await db.researchProject.findUnique({
        where: { id: (await params).id },
        include: {
          creator: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          updater: {
            select: {
              id: true,
              name: true,
              email: true
            }
          },
          versions: {
            include: {
              creator: {
                select: {
                  name: true,
                  email: true
                }
              }
            },
            orderBy: {
              createdAt: 'desc'
            }
          },
          histories: {
            include: {
              user: {
                select: {
                  name: true,
                  email: true
                }
              }
            },
            orderBy: {
              createdAt: 'desc'
            }
          }
        }
      })
    } catch (dbError) {
      console.log('数据库查询失败，使用模拟数据:', dbError)
    }
    
    // 如果数据库中没有找到数据，使用模拟数据
    if (!project) {
      project = {
        _id: (await params).id,
        PROJECT_CODE: 'PROJ-2024-001',
        model: '风机控制器V2.0',
        PROJECT_TYPE_NAME: '风机',
        PROJECT_DESC: '新一代风机控制器，具有高效能、低噪音、智能化控制等特点。采用先进的电机控制算法，支持多种保护功能，适用于各种风机应用场景。',
        PROJECT_PLAN_START_DATE: '2024-01-01',
        PROJECT_PLAN_END_DATE: '2024-06-30',
        status: 2,
        statusDesc: '设计中',
        fullStatusDesc: '设计中 - 方案设计阶段',
        developmentStatus: '设计中',
        completionPercentage: 25,
        progressColor: 'blue',
        WORK_TEMP: '-10度 +50度',
        CERTIFICATION: 'CE, FCC, RoHS',
        LOW_POWER: '100',
        STARTUP_TIME: '1.0',
        CONFORMAL_COATING: '有',
        RATED_VOLTAGE: '24V',
        MAX_POWER: '500',
        MAX_SPEED: '3000',
        POLE_PAIRS: '4',
        HAS_HALL: '有',
        CONTROL_MODE: 'PWM控制',
        CONTROL_ALGORITHM: 'FOC算法',
        STALL_PROTECTION: '有，自恢复',
        OVERVOLTAGE_PROTECTION: '有，自恢复',
        UNDERVOLTAGE_PROTECTION: '有，自恢复',
        TEMPERATURE_PROTECTION: '有，自恢复',
        OVERCURRENT_PROTECTION: '有，自恢复',
        CURRENT_LIMIT_PROTECTION: '有',
        BLOCKAGE_PROTECTION: '有，自恢复',
        PHASE_PROTECTION: '有',
        STALL_HOLD_TIME: '1',
        STALL_RESTART_TIME: '2',
        STALL_RESTART_COUNT: '3',
        OVERVOLTAGE_VALUE: '27',
        OVERVOLTAGE_RECOVERY_VALUE: '25',
        UNDERVOLTAGE_VALUE: '18',
        UNDERVOLTAGE_RECOVERY_VALUE: '20',
        protectionTemp: '100',
        recoveryTemp: '90',
        overcurrentValue: '30',
        currentLimitValue: '25',
        blockageDiameter: '5',
        blockageHoldTime: '3',
        customerName: '苏州成就智能科技有限公司',
        salespersonName: '陈涛',
        requirements: '高效能、低噪音、智能化控制',
        controlDetails: [
          '启动控制：采用软启动方式，启动时间可调，避免电流冲击',
          '运行控制：支持多种控制模式切换，实时监控运行状态',
          '保护控制：多重保护机制，确保设备安全运行',
          '通信控制：支持远程控制和状态监控，便于系统集成'
        ],
        creator: {
          id: 'user-001',
          name: '张工程师',
          email: 'zhang@example.com'
        },
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-15T14:30:00Z'
      }
    }
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error fetching research project:', error)
    return NextResponse.json(
      { error: 'Failed to fetch research project' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    
    const existingProject = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }
    
    const {
      projectTitle,
      name,
      projectCode,
      projectType,
      category,
      applicationType,
      description,
      customerName,
      applicantName,
      projectManagerName,
      priority,
      startDate,
      endDate,
      deadline,
      planStartDate,
      planEndDate,
      updatedBy
    } = body
    
    const project = await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        projectTitle,
        name,
        projectCode,
        projectType,
        category,
        applicationType,
        description,
        customerName,
        applicantName,
        projectManagerName,
        priority,
        startDate: startDate ? new Date(startDate) : null,
        endDate: endDate ? new Date(endDate) : null,
        deadline: deadline ? new Date(deadline) : null,
        planStartDate: planStartDate ? new Date(planStartDate) : null,
        planEndDate: planEndDate ? new Date(planEndDate) : null,
        updatedBy,
        updateTime: new Date()
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: project.id,
        action: 'UPDATED',
        description: '更新研究项目信息',
        userId: updatedBy,
        fromLevel1: existingProject.level1,
        fromLevel2: existingProject.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error updating research project:', error)
    return NextResponse.json(
      { error: 'Failed to update research project' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    await db.researchProject.delete({
      where: { id: (await params).id }
    })
    
    return NextResponse.json({ message: 'Research project deleted successfully' })
  } catch (error) {
    console.error('Error deleting research project:', error)
    return NextResponse.json(
      { error: 'Failed to delete research project' },
      { status: 500 }
    )
  }
}